from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.utils import check_access_token
from users.models import User
from .models import OAuthQQUser
# serializers.Serializer
# serializers.ModelSerializer
# 如果我们选择 ModelSerializer 理论上是可以的 ，但是我们并没有发现 省事的地方
#     access_token
#     sms_code
#     根据手机号判断用户是否注册过

class OAuthQQUserSerializer(serializers.Serializer):

    mobile = serializers.RegexField(regex='1[3-9]\d{9}',label='手机号',required=True)
    password=serializers.CharField(label='密码',required=True)
    sms_code=serializers.CharField(max_length=6,min_length=6,required=True)
    access_token=serializers.CharField()


    def validate(self, attrs):

        # 1. 验证 access_token
        access_token = attrs.get('access_token')
        # access_token 在哪里加密 就去哪里解密
        openid=check_access_token(access_token)

        if openid is None:
            raise serializers.ValidationError('绑定时效过期')

        # 添加openid，传递给 validated_data
        attrs['openid']=openid

        #2. 验证短信验证码
        # 2.1 获取用户提交
        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')
        # 2.2 获取redis的
        redis_conn = get_redis_connection('code')
        redis_sms_code = redis_conn.get('sms_%s' % mobile)
        if redis_sms_code is None:
            raise serializers.ValidationError('短信验证码已过期')
        # 2.3 比对
        if redis_sms_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码错误')

        #3. 判断手机号是否注册
        # 根据手机号查询用户
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 说明此手机号没有注册
            # 创建一个用户
            # 因为此 validate 方法是 主要用于验证，
            # 所以我们将 创建用户的指令放到后边去
            # user = User.objects.create()
            pass
        else:
            #说明此手机号已经注册
            if not user.check_password(attrs.get('password')):
                raise serializers.ValidationError('密码不正确')

            attrs['user']=user

        return attrs

    """
    数据的流向
    data --> attrs -->validated_data
    """

    def create(self, validated_data):

        user  = validated_data.get('user')
        openid = validated_data.get('openid')

        if user is None:
            #说明 没有注册，我们需要手动创建一个用户
            user = User.objects.create(
                username=validated_data.get('mobile'),
                mobile=validated_data.get('mobile'),
                password=validated_data.get('password')
            )
            user.set_password(validated_data.get('password'))
            user.save()

        qquser = OAuthQQUser.objects.create(
            user=user,
            openid=openid
        )

        return qquser
